#include "Sphere.h"
#include "Misc.h"
#include <cmath>
#include <algorithm>

namespace RayTrace{
CSphere::CSphere(void) 
{
	m_type=SPHERE;
}

CSphere::~CSphere(void)
{
}
CSphere::CSphere(vector3 c,float r)
{
	center=c;
	radius=r;
	m_type=SPHERE;
}


double CSphere::InterSection(ray myray)
{

		double A,B,C,D;
		double a,b,c,r;
		double res;
		a=center.x;
		b=center.y;
		c=center.z;
		r=radius;

		vector3 dir=myray.direction;
		vector3 o=myray.origin;
		A=powf(dir.x,2)+powf(dir.y,2)+powf(dir.z,2);
		B=2.0*(dir.x*(o.x-a)+dir.y*(o.y-b)+dir.z*(o.z-c));
		C=powf(o.x-a,2)+powf(o.y-b,2)+powf(o.z-c,2)-powf(r,2);

		D=B*B-4.0*A*C;
		if (D<0.0)
		{
			res=-1.0f;
			return res;
		}
		else
		{
			if (D<minError)
			{
				res=(-B)/(2.0*A);
				return (res);
			}
			else
			{
				res=std::min((-B-sqrt(D)),(-B+sqrt(D)))/(2.0*A);
				return res;
			}
		}
}
vector3 CSphere::GetNormal(vector3 p)
{
	return p-center;
}

}